import Ember from 'ember';
import InfiniteScroll from '../../infinite-scroll';
const { taskApplyStatus_apply,taskApplyStatus_applySuc,taskApplyStatus_applyFail} = Constants;

export default Ember.Controller.extend(InfiniteScroll,{
  feedService: Ember.inject.service('feed-bus'),
  dataLoader: Ember.inject.service("data-loader"),
  dateService: Ember.inject.service("date-service"),
  feedBus: Ember.inject.service("feed-bus"),
  serviceListFlag: 0,
  countListFlag: 0,
  infiniteContentPropertyName: "taskList",
  infiniteModelName: "task",
  infiniteContainerName:"taskSquareContainer",
  panmoveMode: "showFunc",//划动处理，showFunc：显示按钮 delete：删除本条
  curExpService: null,//当前展开的服务内容
  tabFuncs:Ember.computed("taskList",function() {
    var a = new Ember.A();
    var t1 = Ember.Object.create({
      code:"todayTask",
      text:"定时任务",
      numberTip:0
    });
    var t2 = Ember.Object.create({
      code:"finished",
      text:"不定时任务",
      numberTip:0
    });
    a.pushObject(t1);
    a.pushObject(t2);
    return a;
  }),
  switcherDef:Ember.computed(function() {
    var a = new Ember.A();
    var t1 = Ember.Object.create({
      code:"task",
      text:"时间排序",
      icon:"ic-time",
      selected: true
    });
    var t2 = Ember.Object.create({
      code:"user",
      text:"按人排序 ",
      icon:"ic-person",
      selected: false
    });
    a.pushObject(t1);
    a.pushObject(t2);
    return a;
  }),
  dataType:"task",
  oriCountItemId: null,
  todayTaskList:Ember.computed("taskList",function(){
    console.log("taskList compu",this.get("taskList"));
    var list = this.get("taskList").filterBy("status",0);
    console.log("list find",list);
    return list;
  }),
  finishedTaskList:Ember.computed("taskList",function(){
    return this.get("taskList").filterBy("status",1);
  }),

  init: function(){
    var _self = this;
    Ember.run.schedule("afterRender",this,function() {
      //  $("div[name='detail-info']").touchstart();
      //  _self.send("switchTab","detail-info");
      _self.set("clickActFlag","todayTask");
    });
  },
  //查询标志的观察者
  queryObs: function(){
    let _self = this;
    //取得系统时间
    let sysTime = _self.get("dataLoader.sysconfig.sysTime");
    let date = this.get("dateService").timestampToTime(sysTime);
    let workDay = date.getDay();
    let firstSec = this.get("dateService").getFirstSecondStampOfDay(date);
    let lastSec = this.get("dateService").getLastSecondStampOfDay(date);
    //首先查询出当前护工对应的服务对象
    let curuser = this.get('global_curStatus').getUser();
    var createServiceItem = function(){
      let serviceItem = Ember.Object.extend({
        //计划时间
        timeStr:Ember.computed("type","startTimeTab",function(){
          if(this.get("type")===2){
            return null;
          }
          let hour = parseInt(this.get("startTimeTab")/2);
          if(this.get("startTimeTab")%2>0){
            hour = hour + ":30";
          }else{
            hour = hour + ":00";
          }
          return hour;
        }),
        //计次的详情数据
        detailList:Ember.computed("type","applyContent",function(){
          if(this.get("type")===1){
            return;
          }
          let list = new Ember.A();
          let applyContent = this.get("applyContent");
          if(!applyContent||applyContent.length===0){
            return list;
          }
          let l = JSON.parse(applyContent);
          for(let i=0;i<l.length;i++){
            let o = Ember.Object.extend({
              index:i+1,
              indexStr:Ember.computed("index",function(){
                return "第" + this.get("index") + "次:";
              }),
              content:l[i].content,
              showStr:Ember.computed("indexStr",function(){
                return this.get("indexStr") + this.get("content");
              }),
            });
            list.pushObject(o.create());
          }
          return list;
        }),
      });
      return serviceItem.create();
    };
    let serviceItemArray = new Ember.A();
    this.set("serviceItemArray",serviceItemArray);
    //通过设置action进行特殊查询
    this.get("global_ajaxCall").set("action","spec_planService");
    //查询出计时服务项目
    this.store.query("nursingplanitem",{filter:{uid:curuser.get("id")}}).then(function(itemList){
      let index = 0;
      if(itemList.get("length")===0){
        _self.set("planDataPushFlag",true);
        return;
      }
      itemList.forEach(function(item){
        let serviceItem = createServiceItem();
        //设置类型标志
        serviceItem.set("type",1);
        serviceItem.set("busiId",item.get("id"));
        //设置关联数据对象
        serviceItem.set("item",item);
        //设置显示内容
        serviceItem.set("customerId",item.get("plan.customer.id"));
        serviceItem.set("customerName",item.get("plan.customer.name"));
        serviceItem.set("avatarUrl",item.get("plan.customer.avatarUrl"));
        serviceItem.set("customerBed",item.get("plan.customer.bed.name"));
        serviceItem.set("title",item.get("item.item.name"));
        serviceItem.set("desc",item.get("item.item.remark"));
        serviceItem.set("remark",item.get("remark"));
        serviceItem.set("weekTab",item.get("weekTab"));
        serviceItem.set("startTimeTab",item.get("startTimeTab"));
        serviceItemArray.pushObject(serviceItem);
        index++;
        if(index>=itemList.get("length")){
          //设置数据加载完毕标志
          _self.set("planDataPushFlag",true);
        }
      });
    });
    this.get("global_ajaxCall").set("action","spec_countService");
    //查询出计次服务项目
    this.store.query("nursingprojectitem",{filter:{uid:curuser.get("id")}}).then(function(itemList){
      if(itemList.get("length")===0){
        _self.set("projectDataPushFlag",true);
        return;
      }
      let index = 0;
      itemList.forEach(function(item){
        let serviceItem = createServiceItem();
        //设置类型标志
        serviceItem.set("type",2);
        serviceItem.set("busiId",item.get("id"));
        //设置关联数据对象
        serviceItem.set("item",item);
        //设置显示内容
        serviceItem.set("customerId",item.get("project.customer.id"));
        serviceItem.set("customerName",item.get("project.customer.name"));
        serviceItem.set("avatarUrl",item.get("project.customer.avatarUrl"));
        serviceItem.set("customerBed",item.get("project.customer.bed.name"));
        serviceItem.set("title",item.get("item.name"));
        serviceItem.set("desc",item.get("item.remark"));
        serviceItem.set("remark",item.get("remark"));
        serviceItemArray.pushObject(serviceItem);
        index++;
        if(index>=itemList.get("length")){
          //设置数据加载完毕标志
          _self.set("projectDataPushFlag",true);
        }
      });
    });
    //查询出执行情况,查当前护工当天的所有执行内容
    _self.store.query("nursingplanexe",{filter:{
      exeStaff:{id:curuser.get("id")},
      "exeStartTime@$gte":firstSec,
      "exeStartTime@$lte":lastSec
    }}).then(function(itemList){
      let itemArray = new Ember.A();
      _self.set("exeItemArray",itemArray);
      if(itemList.get("length")===0){
        _self.set("exeDataPushFlag",true);
        return;
      }
      let index = 0;
      itemList.forEach(function(item){
        index++;
        //组装对应的业务标识
        if(item.get("itemProject")&&item.get("itemProject.id")){
          item.set("busiId",item.get("itemProject.id"));
        }else{
          item.set("busiId",item.get("itemPlan.id"));
        }
        _self.get("exeItemArray").pushObject(item);
        if(index>=itemList.get("length")){
          //设置数据加载完毕标志
          _self.set("exeDataPushFlag",true);
        }
      });
    });
  }.observes("queryFlag").on("init"),
  //当3组数据都加载完毕，开始进行页面数据组织
  dataBuildObs: function(){
    var _self = this;
    let curuser = this.get('global_curStatus').getUser();
    if(!this.get("planDataPushFlag")||!this.get("projectDataPushFlag")||!this.get("exeDataPushFlag")){
      return;
    }
    let oriarray = this.get("serviceItemArray");
    oriarray = oriarray.sortBy("customerId");
    let exeItemArray = this.get("exeItemArray");
    let serviceList = new Ember.A();
    let customerList = new Ember.A();
    let counterList = new Ember.A();
    let curCustomer = null;
    oriarray.forEach(function(serviceItem){
      //组装按照服务项目排列的数据
      let exeItem = _self.get("exeItemArray").findBy("busiId",serviceItem.get("busiId"));
      if(exeItem){
        //标记已经执行过的
        serviceItem.set("hasApply",true);
        serviceItem.set("exeItem",exeItem);
        serviceItem.set("applyContent",exeItem.get("remark"));
      }
      if(serviceItem.get("type")===2){
        //组装按照客户排列的数据
        let customerIdInloop = serviceItem.get("customerId");
        if(!curCustomer||curCustomer.get("id")!==customerIdInloop){
          curCustomer = Ember.Object.create({
            id:customerIdInloop,
            name:serviceItem.get("customerName"),
            room:serviceItem.get("customerBed"),
            stuffName:curuser.get("name"),
            services: new Ember.A(),
          });
          customerList.pushObject(curCustomer);
        }
        if(exeItem){
          //标记已经执行过的
          curCustomer.set("hasApply",true);
        }
        curCustomer.get("services").pushObject(serviceItem);
      }else{
        serviceList.pushObject(serviceItem);
      }
    });
    this.set("serviceAllList",serviceList);
    this.set("customerList",customerList);
    this.incrementProperty("serviceListFlag");
    this.incrementProperty("countListFlag");
  }.observes("planDataPushFlag","projectDataPushFlag","exeDataPushFlag").on("init"),
  //按时服务列表变化的监视器
  serviceListObs: function(){
    if(this.get("serviceListFlag")===0){
      return;
    }
    //计时服务按服务排序
    this.set("serviceList",this.get("serviceAllList").sortBy("hasApply","weekTab","startTimeTab"));
    //计时服务按客户排序
    this.set("serviceCustomerList",this.get("serviceAllList").sortBy("hasApply","customerId","weekTab","startTimeTab"));
  }.observes("serviceListFlag").on("init"),
  //计次服务列表变化的监视器
  countListObs: function(){
    if(this.get("countListFlag")===0){
      return;
    }
    //计次服务
    this.set("countList",this.get("customerList"));
  }.observes("countListFlag").on("init"),

  refreshTabNumber: function(){
    var _self = this;
    this.get("tabFuncs").forEach(function(tab){
      if(tab.get("code")==="todayTask"){
        tab.set("numberTip",_self.get("todayTaskList.length"));
      }else{
        return;
      }
    });
  },
  /*通过event service监控顶部菜单的选择事件，并进行相关方法调用*/
  listenner: function() {
    console.log("feedService reg");
    this.get('feedService').on('headerEvent_queryTask', this, 'queryTask');
  }.on('init'),
  //注销时清除事件绑定
  cleanup: function() {
    console.log("cleanup feed");
    this.get('feedService').off('headerEvent_queryTask', this, 'queryTask');
  }.on('willDestroyElement'),

  actions:{
    switchTab(code){
      console.log('switchTab in,code:' + code);
      this.set("curTabCode",code);
    },
    switchDataMode(code){
      console.log('switchDataMode in,code:' + code);
      this.set("dataType",code);
    },
    goCountDetail(){
      var mainpageController = App.lookup('controller:business.mainpage');
      mainpageController.switchMainPage('task-count-detail');
    },
    panMoveProcAction(item){
      console.log('panMoveProcAction in,item:' , item);
      /*删除模式*/
      if(this.get("panmoveMode")==="delete"||true){
        this.finishService(item,function(){
          App.lookup("controller:business").popTorMsg("护理任务--" + item.get("title") + ",已完成");
        });
      }
      /*功能按钮显示模式*/
      if(this.get("panmoveMode")==="showFunc"){

      }
    },
    itemCntAdd(serviceItem){
      //通过全局服务进行上下文传值
      this.get("feedBus").set("threadData",serviceItem);
      App.lookup("controller:business.mainpage").switchMainPage("service-counter-apply",{service_id:serviceItem.get("id")});
    },
    countItemExpand(selecedServiceId){
      var _self = this;
      var findService = function(sid){
        var csData = _self.get("countList");
        var curItem = null;
        csData.forEach(function(customerData){
          customerData.get("services").forEach(function(service){
            if(service.get("busiId")===sid){
              curItem = service;
            }
          });
        });
        return curItem;
      };
      var selecedService = findService(selecedServiceId);
      //如果已经展开，则只收起
      if(selecedService.get("expanded")){
        selecedService.set("expanded",false);
        return;
      }
      //否则展开本级，收起其他级
      selecedService.set("expanded",true);
      var curExpService = this.get("curExpService");
      if(curExpService&&curExpService.get("busiId")!==selecedService.get("busiId")){
        curExpService.set("expanded",false);
      }
      this.set("curExpService",selecedService);
    },
    finish(serviceItem){
      this.finishService(serviceItem,function(){
        App.lookup("controller:business").popTorMsg("护理任务--" + serviceItem.get("title") + ",已完成");
      });
    }
  },
  //保存方法
  finishService: function(serviceItem,callback){
    let _self = this;
    let user = this.get("global_curStatus").getUserReal();
    let exeRecord = this.get('store').createRecord("nursingplanexe",{
      exeStaff:user,
    });
    //存储按时或计次的服务情况
    if(serviceItem.get("type")===1){
      let planItem = serviceItem.get("item");
      exeRecord.set("plan",planItem.get("plan"));
      exeRecord.set("itemPlan",planItem);
      //备注信息
      let jsonObj = {};
      let serviceDesc = serviceItem.get("serviceDesc");
      if(serviceDesc){
        jsonObj.serviceDesc = serviceDesc;
      }
      if(serviceItem.get("serviceTag")){
        jsonObj.serviceTag = serviceItem.get("serviceTag");
      }
      exeRecord.set("remark",JSON.stringify(jsonObj));
    }else{
      //如果已经执行过，则使用之前的执行对象
      if(serviceItem.get("hasApply")){
        exeRecord = serviceItem.get("exeItem");
      }
      exeRecord.set("itemProject",serviceItem.get("item"));
      exeRecord.set("remark",serviceItem.get("applyContent"));
    }
    exeRecord.save().then(function(){
      //设置已执行的标志用于页面处理
      serviceItem.set("hasApply",true);
      _self.incrementProperty("serviceListFlag");
      if(callback){
        callback();
      }
    });
  }
});
